﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Collections;
using System.IO;

namespace Web.Enhancements.Rest
{
    public class WebRestMapperModule : IHttpModule
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WebRestMapperModule()
        {
        }

        public void Dispose()
        {
        }

        /// <summary>
        /// Method initializes the class behavior.
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        private void context_BeginRequest(object source, EventArgs e)
        {
            //rewrite REST path for ASP.NET cache to handle mathod as extra parameter.
            System.Web.HttpApplication app = (HttpApplication)source;
            string extention = Path.GetExtension(app.Request.AppRelativeCurrentExecutionFilePath).Replace(".", "");
            if (string.Compare(extention, WebRestSettings.Current.RestFileExtension, true) == 0)
            {
                string queryString = app.Request.QueryString.ToString();
                int ampPos = queryString.IndexOf("&");
                int eqPos = queryString.IndexOf("=");
                //if & (as Method Name end) appears prior "=" sign, this means the method declared and is there without var name. 
                if ((ampPos < eqPos && eqPos > -1 && ampPos > -1) || (eqPos == -1 && ampPos == -1) || (eqPos == -1 && ampPos > -1))
                    app.Context.RewritePath(app.Request.Path, app.Request.PathInfo, string.Format("method={0}", queryString));
            }
        }
    }
}
